package com.loveto.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loveto.common.ImageDownloader;
import com.loveto.common.JsonUtils;
import com.loveto.constant.LovetoConstant;

public class FriendsListActivity extends BaseActivity implements
View.OnClickListener{
	
	// 사용하는 변수들
	private ProgressDialog progressDialog;
	private LinearLayout contentMain;
	private String memberid;
	private String gender;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_friends_list);
		((RelativeLayout)findViewById(R.id.btn_goto_back)).setOnClickListener(this);
		contentMain = (LinearLayout)findViewById(R.id.content_main);
		
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		memberid = pref.getString("memberid", "");
		gender = pref.getString("gender", "");

		progressDialog = new ProgressDialog(FriendsListActivity.this);
		progressDialog.setMessage("정보를 불러오고있습니다.");
		progressDialog.show();
		
		if (isNetworkAvailableAndNotice()) {
			setFriendList();
		}
	}
	
	private void setFriendList() {
		new AsyncTask<Void, RelativeLayout, List<String>>() {
			private List<RelativeLayout> friendLayoutList; // 하나의 row Layout 들을 간직한 List
			
			// 이곳에 포함된 code는 AsyncTask가 execute 되자 마자 UI 스레드에서 실행됨.
			// 작업 시작을 UI에 표현하거나
			// background 작업을 위한 ProgressBar를 보여 주는 등의 코드를 작성.
			@Override
			protected void onPreExecute() {
				progressDialog.setMessage("정보를 불러오고있습니다.");
				progressDialog.show();
				
				// 하나의 row Layout 들을 간직한 List 초기화
				friendLayoutList = new ArrayList<RelativeLayout>();

				Log.d("tag", "Background 작업 시작 ");
				super.onPreExecute();
			}

			// UI 스레드에서 AsynchTask객체.execute(...) 명령으로 실행되는 callback
			@Override
			protected List<String> doInBackground(Void... params) {
				List<String> photoUrlList = null; // 사진url array
				
				try {
					String jsonText = JsonUtils
							.getStringFromUrl(LovetoConstant.FRIEND_LIST_URL + "?memberid=" + memberid + "&gender=" + gender);
					 Log.d("tag", jsonText);
					// 원격에서 읽어온 데이터로 JSON 객체 생성
					try {
						JSONArray jsonArray = new JSONArray(jsonText);
						int jsonArrayLen = jsonArray.length();
						Log.d("tag","길이는?" + jsonArrayLen);

						// 사진을 전체 다운로드를 위하여 // 초기화
						photoUrlList = new ArrayList<String>();
						
						for (int i = 0; i < jsonArrayLen; i++) {
							JSONObject object = jsonArray.getJSONObject(i);
							
							
							RelativeLayout friendLayout = makeRelativeLayout(object, photoUrlList);
							publishProgress(friendLayout);
							// 사진 전체 다운로드를 위하여
							friendLayoutList.add(friendLayout);
						}
						
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				return photoUrlList;
			}
			
			@Override
			protected void onProgressUpdate(RelativeLayout... progress) {
				contentMain.addView(progress[0]);
			}

			@Override
			protected void onPostExecute(List<String> photoUrlList) {
				TextView friendListCountTextView = (TextView)findViewById(R.id.friend_list_count);
				friendListCountTextView.setText("쪽지 친구(" + friendLayoutList.size() + ")");
				// 사진 한꺼번에 다운로드
				ImageDownloader imageDownloader = new ImageDownloader();
				int photoUrlArrayLen = photoUrlList.size();
				for (int i = 0; i < photoUrlArrayLen; i++) {
					String photoUrl = photoUrlList.get(i);
					ImageView imgView = (ImageView) friendLayoutList.get(i)
							.findViewById(R.id.userinfo_photo);
					imageDownloader.download(photoUrl, imgView);
				}
				// 프로그레스 다이얼로그 끄기
				progressDialog.dismiss();

				Log.d("tag", "화면 노출 ");
			}

			// AsyncTask.cancel(boolean) 메소드가 true 인자로
			// 실행되면 호출되는 콜백.
			// background 작업이 취소될때 꼭 해야될 작업은 여기에 구현.
			@Override
			protected void onCancelled() {
				super.onCancelled();
			}
		}.execute();
	}
	
	private RelativeLayout makeRelativeLayout(JSONObject object, List<String> photoUrlList) throws JSONException {
		RelativeLayout friendLayout;
		
		String seq = object.getString("seq");
		String friendid = object.getString("friendid");
		String local = object.getString("local");
		String local_detail = object.getString("local_detail");
		String age = object.getString("age");
		String job = object.getString("job");
		String like_cnt = object.getString("like_cnt");
		String follower_cnt = object.getString("follower_cnt");
		String gender = object.getString("gender");
		
		StringBuffer sb = new StringBuffer();
		sb.append(LovetoConstant.PHOTO_THUMB_URL).append(friendid).append(".jpg");
		photoUrlList.add(sb.toString());
		
		if ("M".equals(gender)) {
			friendLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_friends_list_man, null);
		} else {
			friendLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_friends_list_woman, null);
		}
		
		TextView userinfoTextView = (TextView)friendLayout.findViewById(R.id.userinfo_text);
		TextView followerCntTextView = (TextView)friendLayout.findViewById(R.id.follower_cnt);
		TextView likeCntTextView = (TextView)friendLayout.findViewById(R.id.like_cnt);
		TextView jobTextView = (TextView)friendLayout.findViewById(R.id.job);
		TextView messagememberseqTextView = (TextView)friendLayout.findViewById(R.id.messagememberseq);
		ImageView messageWriteImageView = (ImageView)friendLayout.findViewById(R.id.messageWriteBtn);
		TextView userIDTextView = (TextView)friendLayout.findViewById(R.id.userID);
		userIDTextView.setText(friendid);
		messageWriteImageView.setOnClickListener(this); //쪽지쓰기 버튼에 클릭 리스너 달기
		ImageView userphoto = (ImageView)friendLayout.findViewById(R.id.userinfo_photo);
		userphoto.setOnClickListener(this); //사진
		
		sb = new StringBuffer();
		sb.append(friendid).append(", ");
		sb.append(local).append(" ").append(local_detail).append(", ");
		sb.append(age);
		userinfoTextView.setText(sb);
		followerCntTextView.setText("호감 갖는 이 : " + follower_cnt + "명");
		likeCntTextView.setText("매력점수 : " + like_cnt + "점");
		jobTextView.setText("직업 : " + job);
		messagememberseqTextView.setText(seq);
				
		
		return friendLayout;
	}

	@Override
	public void onClick(View v) {
		RelativeLayout vParent;
		Intent intent;
		switch (v.getId()) {
			case R.id.btn_goto_back:
				finish();
				break;
			case R.id.userinfo_photo:
				vParent = (RelativeLayout)v.getParent();
				TextView v_userID = (TextView)vParent.findViewById(R.id.userID);
				String userID = (String)v_userID.getText();
				intent = new Intent(FriendsListActivity.this, UserinfoViewOthersActivity.class);
				intent.putExtra("memberid_other", userID);
				startActivity(intent);
				break;
			case R.id.messageWriteBtn:
				//영역에 적혀있는 텍스트을 읽고 다음 엑티비티에 전달함.
				vParent = (RelativeLayout)v.getParent();
				
				TextView messagememberseqTextView = (TextView)vParent.findViewById(R.id.messagememberseq);
				String messagememberseq = (String)messagememberseqTextView.getText();

				TextView userinfoTextView = (TextView)vParent.findViewById(R.id.userinfo_text);
				String userinfoText = (String)userinfoTextView.getText();
				
				intent = new Intent(FriendsListActivity.this, MessageFriendActivity.class);
				intent.putExtra("friendInfo", userinfoText);
				intent.putExtra("messageMemberSeq", messagememberseq);
				startActivity(intent);
				break;
		}
	}
	
	
	
}
